﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kaiser.Extensions;
using Kaiser.Modules.Core.Aggregates;
using Kaiser.Modules.Core.Aggregates.Bills;
using Kaiser.Modules.Core.Aggregates.Product;

namespace Kaiser.Modules.Core.Services
{
    public class SaleOrderService : Kaiser.Services.ServiceBase<SaleOrderBills>
    {
        public SaleOrderService()
        {
            SaleOrderFinishEvent += SaleOrderService_SaleOrderFinishEvent;
        }

        public delegate void SaleOrderFinishDelegate(SaleOrderBills item);
        public delegate void AddSaleOrderDelegate(SaleOrderBills item);

        public event SaleOrderFinishDelegate SaleOrderFinishEvent;

        protected virtual void OnSaleOrderFinishEvent(SaleOrderBills item)
        {
            SaleOrderFinishDelegate handler = SaleOrderFinishEvent;
            if (handler != null) handler(item);
        }





        /// <summary>
        /// 转换成流水的记录,存为副本
        /// </summary>
        /// <param name="saleOrder"></param>
        /// <returns></returns>
        private FlowBills ConvertToFlowBills(SaleOrderBills saleOrder)
        {
            var model = new FlowBills();
            model.Balance = new Balance() { BalanceName = "付定金/欠款", BalanceType = BalanceTypeEnum.收入 };
            model.BillsDescp = saleOrder.Remark;
            model.CreatetDateTime = DateTime.Now;
            model.InAmount = saleOrder.GetAmount;
            model.CurAmonut = FlowBills.GetLastAmount() + model.InAmount;
            model.Company = saleOrder.Company;
            model.SettleAcct = saleOrder.SettleAcct;
            model.BillCode = saleOrder.BillCode;
            model.User = saleOrder.User;
            return model;
        }

        public override void Add(SaleOrderBills model)
        {
            SaleOrderBills.Add(model);
            SaleOrderFinishEvent(model);
        }

        void SaleOrderService_SaleOrderFinishEvent(SaleOrderBills item)
        {
            ////对应产品的库存同时消减掉;
            //item.SaleOrderBillItems.ForEach(x => x.Product.UpdateCurStock(x.Product.CurStock - x.ItemCount));

            //添加到流水账户里面
            CoreServiceFactory.CreateFlowBillsService().AddFlowBills(ConvertToFlowBills(item));

        }

      
    }
}
